var setRoleId;
var actionIds;
$(function() {
	loadTableInfo();
	
	loadRoleTree(null);
	
});

//加载 权限Table
function loadTableInfo(){
	var table = $('#tableinfo').DataTable();
	$('#tableinfo').dataTable({
		"ajax": $.ctx + "/sysrole/findByPage.do",
		"processing": true,
        "serverSide": true,
        "ordering": false,
		"dom": '<"top"><"toolbar">rt<"bottom"lp><"clear">',//table布局(可更换位置)：r加载等待显示信息|t表格|l每页显示多少|p分页按钮|f搜索框
	    "destroy": true,//每次加载，销毁原有table
        "columns": [
            { "data": null },
            { "data": "name" },
            { "data": "role" },
            { "data": "status" },
            { "data": null }
        ],
        "columnDefs": [
			   {"targets": 0,
			    "render" : function(data, type, row, where) {
					return '<input type="checkbox" name="id" value="'+data.id+'" />';}
			   },
               {"targets": 3,
            	"render" : function(data, type, row, where) {
            		return row.status==0?"正常":"停用";}
               },
               {"targets": 4,
                "render" : function(data, type, row, where) {
                	var html = '';
                	html += '&nbsp;<button type="button" class="btn btn-default btn-xs" onclick="loadRoleTree('+data.id+');">配置</button>';
                	html += '&nbsp;<button type="button" class="btn btn-default btn-xs" onclick="stopRole('+data.id+');">停用</button>';
                	return html;}
               }
        ]
    });
	//增加自定义按钮
	var buttonhtml  = '&nbsp;<button type="button" class="btn btn-success" onclick="createDialog()" >添加</button>';
	$("div.toolbar").html(buttonhtml);
}

//加载 权限Tree
function loadRoleTree(roleId){
	setRoleId = roleId;//设置权限ID给全局变量
	$("#roleTree").jstree("destroy");
	$('#roleTree').jstree({
		'plugins' : [ "wholerow", "checkbox" ],
		'core' : {
			'data' : {
				'url' : '/springsecurity/sysrole/getSysRole.do?roleId='+roleId,
				'dataType': 'JSON'
			}
		}
	});
	loadRoleTreeChange();
}

//加载 权限Tree 变更操作
function loadRoleTreeChange(){
	$('#roleTree').on('changed.jstree', function(e,data) {
		//console.log(e);
		actionIds = data.selected.toString();
    });
}

//
function stopRole(roleId){
	
}

//显示 - 添加权限
function createDialog(){
	$("#saveSysRolePage").modal("show");
}
//添加权限
function saveSysRole(){
	$.ajax({
		url : $.ctx + "/sysrole/saveSysRole.do",
		type : "post",
		data : {
			"name" : $("#fm #name").val(),
			"role" : $("#fm #role").val()
		},
		dataType : "json",
		success : function(result){
			if (result.msg == '操作成功') {
				$("#saveSysRolePage").modal("hide");
				loadTableInfo();
				toastr.success(result.msg);
			}else{
				toastr.warning(result.msg);
			}
		}
	});
}

//配置权限
function setSysRole(){
	$.ajax({
		url : $.ctx + "/sysrole/setSysRole.do",
		type : "post",
		data : {
			"setRoleId" : setRoleId,
			"actionIds" : actionIds
		},
		dataType : "json",
		success : function(result){
			if (result.msg == '操作成功') {
				toastr.success(result.msg);
			}else{
				toastr.warning(result.msg);
			}
		}
	});
	
}